﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Data;
using Newtonsoft.Json;
using Framework.DataAccess;
using Framework.Common.JsonEntities;
using Framework.Common;
using Framework.Common.Common;
using Mode;
using System.Text;

namespace WebSite.WebServer
{
    /// <summary>
    /// TopicMng 的摘要说明
    /// </summary>
    public class TopicMng : IHttpHandler, IRequiresSessionState
    {
        JsonReturnMessages msg;
        public void ProcessRequest(HttpContext context)
        {
            msg = new JsonReturnMessages();
            try
            {
                string action = context.Request.Params["Action"];
                if (action == "TopicRoleTree")
                    TopicRoleTree();
                else if (action == "TopicRoleList")
                    TopicRoleList();
                else if (action == "RoleList")
                    GetRoleList();
                else if (action == "SaveTopic")
                    SaveTopic();
                else if (action == "TopicByID")
                    GetTopicByID();
                else if (action == "AnswerListByID")
                    GetAnswerList();
                else if (action == "TopicRoleListByID")
                    GetTopicRoleList();
                else if (action == "SetTopicStatus")
                    SetTopicStatus();
            }
            catch (Exception err)
            {
                var message = err.Message;
                if (err.InnerException != null && err.InnerException.Message != null)
                    message += "<BR>" + err.InnerException.Message;

                msg.IsSuccess = 0;
                msg.Msg = message;

                var json = JsonConvert.SerializeObject(msg);
                context.Response.Write(json);
            }
            context.Response.End();
        }

        /// <summary>
        /// 检查是否登录
        /// </summary>
        /// <returns></returns>
        private loginInfo chklogin()
        {
            try
            {
                return SessionShard.loginUser;
            }
            catch
            {
                msg.IsSuccess = -9;
                msg.Msg = "登陆失效，请重新登陆!";
                return null;
            }
        }

        /// <summary>
        /// 获取题型角色树
        /// </summary>
        private void TopicRoleTree()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            StringBuilder sbJosn = new StringBuilder();
            Topic topic = new Topic();
            DataView dvTopicRole = topic.GetTopicTypeRoleList();
            //先固定输出6大题型
            Dictionary<int, string> topicTypeList = new Dictionary<int, string>();
            topicTypeList.Add(1, "单项选择题");
            topicTypeList.Add(2, "多项选择题");
            topicTypeList.Add(3, "判断题");
            topicTypeList.Add(4, "填空题");
            topicTypeList.Add(5, "问答题");
            topicTypeList.Add(6, "打字题");
            foreach (int key in topicTypeList.Keys)
            {
                string strType = string.Format("'id':'{0}','role':'-1','text':'{1}'", key, topicTypeList[key]).Replace("'", "\"");
                //输出题型角色
                dvTopicRole.RowFilter = string.Format("T_TYPE={0}", key);
                string strRole = "";
                foreach (DataRowView drv in dvTopicRole)
                {
                    string str = string.Format("'id':'{0}','role':'{1}','text':'{2}'", Convert.ToString(drv["T_TYPE"]),
                        Convert.ToString(drv["R_ID"]), Convert.ToString(drv["R_NAME"])).Replace("'", "\"");
                    strRole += "{" + str + "},";
                }
                sbJosn.Append("{" + strType + @",""children"":[" + strRole.TrimEnd(',') + @"]},");
            }
            context.Response.Write("[" + sbJosn.ToString().TrimEnd(',') + "]");
        }

        /// <summary>
        /// 查找题型角色列表
        /// </summary>
        private void TopicRoleList()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }

            Topic topic = new Topic();

            int? typeID = context.Request.Params["typeID"].ToIntNull();
            int? roleID = context.Request.Params["roleID"].ToIntNull();
            DateTime? beginDate = context.Request.Params["beginDate"].ToDateNull();
            DateTime? endDate = context.Request.Params["endDate"].ToDateNull();
            string title = context.Request.Params["title"];
            int status = context.Request.Params["status"].ToInt();

            PageView pageInfo = new PageView();
            pageInfo.PageIndex = context.Request.Params["page"].ToInt(1);
            pageInfo.PageSize = context.Request.Params["pagesize"].ToInt(20);
            pageInfo.SortName = context.Request.Params["sortname"].ToStr();
            pageInfo.SortOrder = context.Request.Params["sortorder"].ToStr();
            pageInfo.SearchParams = context.Request.Params;


            PageList<object> List = topic.GetTopicList(pageInfo, status, (typeID <= 0 ? null : typeID), roleID, beginDate, endDate, title);

            string Rjson = @"{""Rows"":null,""Total"":""0""}";
            if (List.Data != null)
            {
                Rjson = @"{""Rows"":" + List.Data.ToJson() + @",""Total"":""" + List.Total + @"""}";
            }
            context.Response.Write(Rjson);
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        public void GetRoleList()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            role myRole = new role();
            IList<role_table> roleList = myRole.GetRolist(true);
            context.Response.Write(JsonConvert.SerializeObject(roleList));
        }

        /// <summary>
        /// 保存题目数据
        /// </summary>
        public void SaveTopic()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            string str = context.Request.Params["topic"];
            topic_table topicData = JsonConvert.DeserializeObject<topic_table>(str);
            topicData.status = 0;
            topicData.date = DateTime.Now;
            str = context.Request.Params["anserList"];
            List<answer_table> answerList = JsonConvert.DeserializeObject<List<answer_table>>(str);
            foreach (answer_table answerData in answerList)
                answerData.date = DateTime.Now;
            str = context.Request.Params["roleList"];
            List<int> roleList = JsonConvert.DeserializeObject<List<int>>(str);
            Topic myTopic = new Topic(true);
            int topicID = topicData.id;
            bool succFlag = false;
            if (topicID == 0)
            {
                topicID = myTopic.AddTopic(topicData, answerList, roleList);
                succFlag = topicID > 0;
            }
            else
                succFlag = myTopic.UpdateTopic(topicData, answerList, roleList);
            msg.IsSuccess = succFlag ? 1 : 0;
            var json = JsonConvert.SerializeObject(msg);
            context.Response.Write(json);
        }

        /// <summary>
        /// 获取题目数据
        /// </summary>
        /// <param name="topicID"></param>
        public void GetTopicByID()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            int topicID = context.Request.Params["TopicID"].ToInt(0);
            Topic myTopic = new Topic();
            topic_table topicData = myTopic.GetTopicByID(topicID);
            context.Response.Write(JsonConvert.SerializeObject(topicData));
        }

        /// <summary>
        /// 获取题目选项
        /// </summary>
        /// <param name="topicID"></param>
        public void GetAnswerList()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            int topicID = context.Request.Params["TopicID"].ToInt(0);
            Topic myTopic = new Topic();
            IList<answer_table> answerList = myTopic.GetAnserListByID(topicID);
            context.Response.Write(JsonConvert.SerializeObject(answerList));
        }

        /// <summary>
        /// 获取题目角色列表
        /// </summary>
        /// <param name="topicID"></param>
        public void GetTopicRoleList()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            int topicID = context.Request.Params["TopicID"].ToInt(0);
            Topic myTopic = new Topic();
            IList<int> roleList = myTopic.GetTopicRoleList(topicID);
            context.Response.Write(JsonConvert.SerializeObject(roleList));
        }

        /// <summary>
        /// 修改题目状态
        /// </summary>
        private void SetTopicStatus()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo loginUser = chklogin();
            if (loginUser == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(msg));
                return;
            }
            int topicID = context.Request.Params["TopicID"].ToInt(0);
            int status = context.Request.Params["Status"].ToInt(0);
            Topic myTopic = new Topic();
            bool succFlag = myTopic.SetTopicStatus(topicID, status);
            if (succFlag)
                msg.IsSuccess = 1;
            var json = JsonConvert.SerializeObject(msg);
            context.Response.Write(json);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}